package common.netty.server.codec;

import common.RpcResponse;
import common.serializer.Serializer;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageEncoder;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
@Slf4j
public class ServerProtocolEncoder extends MessageToMessageEncoder<RpcResponse> {

    @Override
    protected void encode(ChannelHandlerContext ctx, RpcResponse responseMessage, List<Object> out) throws Exception {
        ByteBuf buffer = ctx.alloc().buffer();

        byte[] bytes = responseMessage.serialize(responseMessage);
        buffer.writeInt(bytes.length);
        buffer.writeBytes(bytes);
        log.info("server响应完数据并序列化完成，返回结果为:{},长度是:{}", responseMessage, bytes.length);

        out.add(buffer);
    }
}
